﻿using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace HelperLibrary
{
    /// <summary>
    /// Http辅助类
    /// </summary>
    public class HTTPHelper
    {
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
           SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        /// <summary>
        /// Get方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static T Get<T>(string url, string token = null, int timeout = 100000)
        {
            string res = HttpGet(url, token, timeout);
            return JsonConvert.DeserializeObject<T>(res);
        }

        /// <summary>
        /// Get
        /// </summary>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string token = null, int timeout = 100000)
        {
            string responseText = string.Empty;
            HttpWebRequest request;
            if (url.StartsWith("https", System.StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
                                                       SecurityProtocolType
                                                           .Tls12; //必须加上这一句，根据需要更改值                                                                                                                        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                request = (HttpWebRequest)WebRequest.Create(url);
                request.ProtocolVersion = HttpVersion.Version11;
            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(url);
            }
            request.Method = "get";
            request.ContentType = "application/json;charset=UTF-8";
            request.Timeout = timeout;
            if (!string.IsNullOrEmpty(token))
            {
                request.Headers.Add("token", token);
            }
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            responseText = myreader.ReadToEnd();
            myreader.Close();
            return responseText;
        }
    }
}
